package com.travel.sight.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.travel.common.utils.R;
import com.travel.common.vo.MemberRespVo;
import com.travel.sight.service.CollectionService;
import com.travel.sight.service.LikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static com.travel.common.constant.AuthServerConstant.LOGIN_USER;

@Controller
@Slf4j
public class LikeWebController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    LikeService likeService;

    @Autowired
    CollectionService collectionService;


    /**
     * 点赞方法
     * @param attractionId
     * @return
     */
    @GetMapping("/saveLike")
    public String saveLike(@RequestParam("attractionId")Integer attractionId){
        //1. 从redis中取出用户信息
        String s = redisTemplate.opsForValue().get(LOGIN_USER);
        MemberRespVo memberRespVo = JSON.parseObject(s,MemberRespVo.class);
        Integer userId = memberRespVo.getMemberId().intValue();

        //2. 判断是否点赞过
        Boolean isLike = likeService.isLike(attractionId, userId);

        //3. 更新点赞后的一系列操作
        likeService.updateAfterLike(attractionId,userId,isLike);

        //http://sight.travel.com/43.html
        return "redirect:http://sight.travel.com/"+attractionId+".html";
    }

    /**
     * 获取点赞和收藏的状态
     * @param attractionId
     * @return
     */
    @GetMapping("/getInitialStatus")
    public R getInitialStatus(@RequestParam("attractionId")Integer attractionId){
        //1. 从redis获取用户信息
        String s = redisTemplate.opsForValue().get(LOGIN_USER);
        MemberRespVo memberRespVo = JSON.parseObject(s,MemberRespVo.class);
        Integer userId = memberRespVo.getMemberId().intValue();

        //2. 获取点赞状态
        Boolean isLike = likeService.isLike(attractionId,userId);

        //3. 获取收藏状态
        Boolean isCollection = collectionService.isCollection(attractionId,userId);

        System.out.println("isLike=="+isLike);
        System.out.println("isCollection=="+isCollection);

        return R.ok().put("isLike",isLike).put("isCollection",isCollection);
    }
}
